//
//  AddressViewController.m
//  ChatDemo-UI2.0
//
//  Created by 小热狗 on 15/7/10.
//  Copyright (c) 2015年 小热狗. All rights reserved.
//

#import "AddressViewController.h"

#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
@interface AddressViewController ()
@property (nonatomic,strong)UISearchBar *search;
@property (nonatomic,strong)UISearchDisplayController * searchPlay;
@property (nonatomic,strong)NSArray *resultsArr;//搜索文字结果

@end

@implementation AddressViewController

- (void)viewDidLoad {
    self.navigationController.navigationBar.hidden = YES;
    [self drawNavWithTitle:@"通讯录"];
    [self drawBackButton];
    [self post];
//    self.automaticallyAdjustsScrollViewInsets=NO;
//    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
//    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
//    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//    [self.navigationItem setLeftBarButtonItem:backItem];
    self.view.backgroundColor=LIGHTGRAYBACKCOLOR;
    [self drawSearch];
    
    self.myTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 104, KScreenWidth, KScreenHeight - 104)];
    self.myTableView.delegate=self;
    self.myTableView.dataSource=self;
    [self.view addSubview:self.myTableView];
    
    
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)drawSearch{
    _search = [[UISearchBar alloc] initWithFrame:CGRectMake(0,64, KScreenWidth,40)];
    
    _search.backgroundColor = [UIColor redColor];
    
    _search.delegate =self;
    
    _search.showsCancelButton =NO;
    
    //    _search.keyboardType =UIKeyboardTypeDefault;
    
    //    [self.view addSubview:_search];
    //    self.myTableView.tableHeaderView = _search;
    [self.view addSubview:_search];
    
    _searchPlay = [[UISearchDisplayController alloc]initWithSearchBar:self.search contentsController:self];
    
    _searchPlay.delegate =self;
    
    
    _searchPlay.searchResultsDataSource =self;
    
    _searchPlay.searchResultsDelegate =self;
    
    _searchPlay.active =NO;
    
    _searchPlay.searchResultsTableView.frame = CGRectMake(0, 164+ 40, KScreenWidth, KScreenHeight - 104);
//    _searchPlay.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
 
}



-(void)post{
    //取得本地通信录名柄
    
    // [self showHudInView:self.view hint:@"正在加载通讯录..."];
    
//    _nameArray=[[NSMutableArray alloc]init];
//    _phoneArray=[[NSMutableArray alloc]init];
   
    ABAddressBookRef tmpAddressBook = nil;
    
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        tmpAddressBook=ABAddressBookCreateWithOptions(NULL, NULL);
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(tmpAddressBook, ^(bool greanted, CFErrorRef error){
            dispatch_semaphore_signal(sema);
        });
        
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else
    {
        tmpAddressBook =ABAddressBookCreate();
    }
    //取得本地所有联系人记录
    
    
    if (tmpAddressBook==nil) {
        return ;
    };
    NSArray* tmpPeoples = (NSArray*)ABAddressBookCopyArrayOfAllPeople(tmpAddressBook);
    _tXLARy = [[NSMutableArray alloc]init];
    for(id tmpPerson in tmpPeoples)
        
    {
        
        NSMutableDictionary *txDic = [[NSMutableDictionary alloc]init];
        //获取的联系人单一属性:First name
        
        NSString* tmpFirstName = (NSString*)ABRecordCopyValue(tmpPerson, kABPersonFirstNameProperty);
        
        NSLog(@"First name:%@", tmpFirstName);
        
        [tmpFirstName release];
        
        //获取的联系人单一属性:Last name
        
        NSString* tmpLastName = (NSString*)ABRecordCopyValue(tmpPerson, kABPersonLastNameProperty);
        
        NSLog(@"Last name:%@", tmpLastName);
        
        [tmpLastName release];
        
        
        
        
        if ([tmpFirstName isEqual:[NSNull null]]||tmpFirstName==nil) {
            tmpFirstName=@"";
        }
        
        if ([tmpLastName isEqual:[NSNull null]]||tmpLastName==nil) {
            tmpLastName=@"";
        }
        
        
        
        NSString *name=[tmpLastName stringByAppendingString:tmpFirstName];
        
//        [_nameArray  addObject:name];
        
        [txDic setObject:name forKey:@"name"];
        //获取的联系人单一属性:Nickname
        
        NSString* tmpNickname = (NSString*)ABRecordCopyValue(tmpPerson, kABPersonNicknameProperty);
        
        NSLog(@"Nickname:%@", tmpNickname);
        
        [tmpNickname release];
        
        //获取的联系人单一属性:Company name
        
        //        NSString* tmpCompanyname = (NSString*)ABRecordCopyValue(tmpPerson, kABPersonOrganizationProperty);
        //
        //        NSLog(@"Company name:%@", tmpCompanyname);
        //
        //        [tmpCompanyname release];
        //
        //        //获取的联系人单一属性:Job Title
        //
        //        NSString* tmpJobTitle= (NSString*)ABRecordCopyValue(tmpPerson, kABPersonJobTitleProperty);
        //
        //        NSLog(@"Job Title:%@", tmpJobTitle);
        //
        //        [tmpJobTitle release];
        //
        //        //获取的联系人单一属性:Department name
        //
        //        NSString* tmpDepartmentName = (NSString*)ABRecordCopyValue(tmpPerson, kABPersonDepartmentProperty);
        //
        //        NSLog(@"Department name:%@", tmpDepartmentName);
        //
        //        [tmpDepartmentName release];
        //
        //        //获取的联系人单一属性:Email(s)
        //
        //        ABMultiValueRef tmpEmails = ABRecordCopyValue(tmpPerson, kABPersonEmailProperty);
        //
        //        for(NSInteger j = 0; ABMultiValueGetCount(tmpEmails); j++)
        //
        //        {
        //
        //            NSString* tmpEmailIndex = (NSString*)ABMultiValueCopyValueAtIndex(tmpEmails, j);
        //
        //            NSLog(@"Emails%d:%@", j, tmpEmailIndex);
        //
        //            [tmpEmailIndex release];
        //
        //        }
        //
        //        CFRelease(tmpEmails);
        //
        //        //获取的联系人单一属性:Birthday
        //
        //        NSDate* tmpBirthday = (NSDate*)ABRecordCopyValue(tmpPerson, kABPersonBirthdayProperty);
        //
        //        NSLog(@"Birthday:%@", tmpBirthday);
        //
        //        [tmpBirthday release];
        //
        //        //获取的联系人单一属性:Note
        //
        //        NSString* tmpNote = (NSString*)ABRecordCopyValue(tmpPerson, kABPersonNoteProperty);
        //
        //        NSLog(@"Note:%@", tmpNote);
        //
        //        [tmpNote release];
        
        //获取的联系人单一属性:Generic phone number
        
        ABMultiValueRef tmpPhones = ABRecordCopyValue(tmpPerson, kABPersonPhoneProperty);
        
        
        NSString *phoneNumber = nil;
        
     
        
        for(NSInteger j = 0; j < ABMultiValueGetCount(tmpPhones); j++)
            
        {
            
           
            
            NSString* tmpPhoneIndex = (NSString*)ABMultiValueCopyValueAtIndex(tmpPhones, j);
            phoneNumber=tmpPhoneIndex;
            if ([phoneNumber isEqual:[NSNull null]]||phoneNumber==nil) {
                phoneNumber=@"空";
                
            }else{
                
                NSArray *_arr = [tmpPhoneIndex componentsSeparatedByString:NSLocalizedString(@"-", nil)];
                phoneNumber= [_arr componentsJoinedByString:@""];
            }
            
            if (ABMultiValueGetCount(tmpPhones)>1) {
                if (j!=0) {
//                    [_nameArray addObject:name];
                    [txDic setObject:name forKey:@"name"];
                }
            }
            
            [_phoneArray addObject:phoneNumber];
            
            [txDic setObject:phoneNumber forKey:@"phone"];
            
            [_tXLARy addObject:txDic];
            
            
            
            NSLog(@"tmpPhoneIndex%d:%@", j, tmpPhoneIndex);
            
            [tmpPhoneIndex release];
            
        }
        
        CFRelease(tmpPhones);
        
    }
    
    
    [self.myTableView reloadData];
    
    
    
    

    
}
- (void)back
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUntreatedApplyCount" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    NSInteger row = 0;
    
    if ([tableView isEqual:self.searchPlay.searchResultsTableView]) {
        
        row = [self.resultsArr count];
        
    }else if ([tableView isEqual:_myTableView]){
        
        if ([_tXLARy isEqual:[NSNull null]]) {
            return 0;
        }else{
           row = _tXLARy.count;
        }

        
    }
    
    return row;
    

    
//    if ([_nameArray isEqual:[NSNull null]]) {
//        return 0;
//    }
//    
//    return _nameArray.count;
   // return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    long row=[indexPath row];
    static NSString *cellIdentifier = @"DataTableCellId";
    //    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    
   
    if ([tableView isEqual:_myTableView]) {
        cell.textLabel.text=[[_tXLARy objectAtIndex:row]objectForKey:@"name"];
    }else{
        cell.textLabel.text=[[_resultsArr objectAtIndex:row]objectForKey:@"name"];
    }
   
     cell.textLabel.font=[UIFont systemFontOfSize:13];
  
    return cell;


}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView cellForRowAtIndexPath:indexPath].selected = NO;
    
    if ([tableView isEqual:_myTableView]) {
        if (_type == 10) {
            NSString *phone=[[_tXLARy objectAtIndex:indexPath.row]objectForKey:@"phone"];
            
            if (phone.length != 11) {
                [TCUtils showAlertViewWithTitle:@"提示" message:@"请选择正确的手机号码!" delegate:nil cancel:@"确定" other:nil tag:0];
            }else{
                self.block(phone);
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        }else{
            
            NSString *name=[[_tXLARy objectAtIndex:indexPath.row]objectForKey:@"name"];
            NSString *phone=[[_tXLARy objectAtIndex:indexPath.row]objectForKey:@"phone"];
            
            
            [self.delegate selectName:name telephone:phone tag:self.type];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
    }else{
        if (_type == 10) {
            NSString *phone=[[_resultsArr objectAtIndex:indexPath.row]objectForKey:@"phone"];
            
            if (phone.length != 11) {
                [TCUtils showAlertViewWithTitle:@"提示" message:@"请选择正确的手机号码!" delegate:nil cancel:@"确定" other:nil tag:0];
            }else{
                self.block(phone);
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        }else{
            
            NSString *name=[[_resultsArr objectAtIndex:indexPath.row]objectForKey:@"name"];
            NSString *phone=[[_resultsArr objectAtIndex:indexPath.row]objectForKey:@"phone"];
            
            
            [self.delegate selectName:name telephone:phone tag:self.type];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
 
    }
    


}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.text = @"";
    searchBar.frame = CGRectMake(0, 20, KScreenWidth, 40);
}

#pragma mark UISearchDisplayControllerDelegate

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    searchBar.frame = CGRectMake(0, 64, KScreenWidth, 40);
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.frame = CGRectMake(0, 64, KScreenWidth, 40);
    
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    
    
    
    return YES;
}



//text是输入的文本,scope是搜索范围

- (void) searchText:(NSString *)text andWithScope:(NSString *)scope
{
    
    //CONTAINS是字符串比较操作符，
    
    if(![text isEqualToString:@""]){
        
        //     NSPredicate *result = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",text];
        
//        NSPredicate *result = [NSPredicate predicateWithFormat:@"name contains[cd]%@",text];
        NSPredicate *result = [NSPredicate predicateWithFormat:@"name contains[cd] %@",text];
        
        self.resultsArr = [self.tXLARy filteredArrayUsingPredicate:result];
        
    }
}

- (BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{
    
    // searchString 是输入的文本
    
    //返回结果数据读取搜索范围 在选择范围
    
    NSArray *searScope = [self.searchPlay.searchBar scopeButtonTitles]; //数组范围
    
    [self searchText:searchString andWithScope:[searScope objectAtIndex:[self.searchPlay.searchBar selectedScopeButtonIndex]]];
    
    return YES;
    
}

- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    [_search setShowsCancelButton:YES];
    for (UIView *v in _search.subviews) {
        if ([v isKindOfClass:[UIButton class]]) {
            [(UIButton *)v setTitle:@"返回" forState:UIControlStateNormal];
        }
    }
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)funcationClick:(UIButton *)sender {
}
@end
